package Concurrency2.Chapter03_CAS_Atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * Instruction：JUC数组原子类的API测试
 * Author：@author MaLi
 */
public class T06_AtomicIntegerArray {

    private static final Object lock = new Object();
    private static final CountDownLatch latch = new CountDownLatch(10);
    private static final int TURN = 100000;//10万
    private static final int THREADS_COUNT = 10;

    public static void main(String[] args) throws InterruptedException {

        fatLock();
        //atomicArray();
    }

    private static void atomicArray() throws InterruptedException {
        long start = System.currentTimeMillis();
        int[] array = {0, 0, 0, 0, 0, 0};
        AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(array);
        //创建多线程
        ExecutorService pool = Executors.newFixedThreadPool(10);

        //submit task: accumulate 10000times / thread = 10 * 10000
        for (int j = 0; j < THREADS_COUNT; j++) {
            pool.submit(() -> {
                for (int i = 0; i < TURN; i++) {
                    atomicIntegerArray.incrementAndGet(0);
                }
                latch.countDown();
            });
        }
        latch.await();
        System.out.println(atomicIntegerArray.get(0));
        System.out.println("Time wasted: " + (System.currentTimeMillis() - start));
        pool.shutdownNow();
    }

    private static void fatLock() throws InterruptedException {
        long start = System.currentTimeMillis();
        int[] array = {0, 0, 0, 0, 0, 0};
        //创建多线程
        ExecutorService pool = Executors.newFixedThreadPool(10);

        //submit task: accumulate 10000times / thread = 10 * 10000
        for (int j = 0; j < THREADS_COUNT; j++) {
            pool.submit(() -> {
                for (int i = 0; i < TURN; i++) {
                    synchronized (lock) {
                        array[0]++;
                    }
                }
                latch.countDown();
            });
        }
        latch.await();
        System.out.println(array[0]);
        System.out.println("Time wasted: " + (System.currentTimeMillis() - start));
        pool.shutdownNow();
    }
}
